package com.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.component.domain.MJob;
import com.component.domain.vo.JobVo;
import com.component.enumitem.JobEnum;
import com.component.service.MJobService;
import com.system.common.Result;
import com.system.job.*;
import com.system.util.EnumToListConverter;
import com.system.util.ReflectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.*;

/**
 * @Classname JobApi
 * @Description TODO
 * @Date 2023/9/22 9:27
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@RestController
@RequestMapping("/job")
public class JobApi {

    @Autowired
    private JobConfig jobConfig;

    @Autowired
    private QuarztUtils quarztUtils;

    @Autowired
    private MJobService mJobService;

    @GetMapping("/getjobtimetype")
    public JSONObject getJobTimeType(){
        QuartzTimeEnum[] quartzTimeEnum= QuartzTimeEnum.values();
        List<Map<String,Object>> mapList=EnumToListConverter.convert(quartzTimeEnum,"type","typeName");
        return Result.successInfo(mapList);
    }

    @GetMapping("/getjoblist")
    public JSONObject getCLassJobApi(){
        Map<String,Object> map=jobConfig.getClassObject();
        List<Map<String,Object>> maps=new ArrayList<>();
        for(String key:map.keySet()){
            Object object=map.get(key);
            String clazz=object.getClass().getName();
            System.out.println(clazz);
            MJob mJob=mJobService.getMJobByMethodCLazz(clazz);
            if(mJob != null){
                continue;
            }
            Class< ? > cls = object.getClass();
            Job job=cls.getAnnotation(Job.class);
            Map<String, Object> obj = new HashMap<>();
            obj.put("key",key);
            obj.put("clazz",object.getClass().getName());
            obj.put("clazzName",object.getClass().getName()+"/"+job.name());
            maps.add(obj);
        }
        return Result.successInfo(maps);
    }

    @GetMapping("/getclassexist")
    public JSONObject getCLassExist(@RequestParam(value = "clazz",required = false)String clazz){
        if(!StringUtils.isNotBlank(clazz)){
            return Result.errorInfo("clazz不得为空");
        }
        boolean exist=ReflectUtils.existsClazz(clazz);
        return Result.successInfo(exist);
    }

    @GetMapping("/getclassmethod")
    public JSONObject getClassMethod(@RequestParam(value = "clazzName",required = false)String clazz){
        if(!StringUtils.isNotBlank(clazz)){
            return Result.errorInfo("clazzName参数不得为空");
        }
        Class<?> cls=ReflectUtils.getClass(clazz);
        if(cls == null){
            return Result.successInfo(clazz+"类不存在");
        }
        Method[] methods=cls.getDeclaredMethods();
        JSONArray array=new JSONArray();
        for (Method method : methods) {
            JSONObject obj=new JSONObject();
            obj.put("method",method.getName());
            array.add(obj);
        }
        return Result.successInfo(array);
    }

    @GetMapping("/getjobtype")
    public JSONObject getJobType(){
        JobEnum[] jobEnum=JobEnum.values();
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < jobEnum.length; i++) {
            JSONObject jsonObject = new JSONObject();
            JobEnum job=jobEnum[i];
            jsonObject.put("status",job.getStatus().toString());
            jsonObject.put("name",job.getJobName());
            jsonArray.add(jsonObject);
        }
        return Result.successInfo(jsonArray);
    }

    @GetMapping("/page")
    public JSONObject page(@RequestParam("pageNum")Integer pageNum,
                           @RequestParam("pageSize") Integer pageSize){
        IPage<MJob> iPage=mJobService.page(pageNum, pageSize);
        return Result.successInfo(iPage);
    }

    @GetMapping("/getjob")
    public JSONObject getJob(@RequestParam("id")String id){
        MJob mJob=mJobService.getById(id);
        return Result.successInfo(mJob);
    }

    @PostMapping("/update")
    public JSONObject update(@RequestBody JobVo jobVo){
        if(jobVo.getId()==null){
            return Result.errorInfo("数据id不得为null");
        }
        MJob mJob=mJobService.getById(jobVo.getId());
        if(jobVo.getJobname()!=null){
            mJob.setJobname(jobVo.getJobname());
        }
        if(jobVo.getCron()!=null){
            mJob.setCron(jobVo.getCron());
        }
        if(jobVo.getTimetype()!=null){
            mJob.setTimetype(jobVo.getTimetype());
        }
        if(jobVo.getMethodclazz()!=null){
            mJob.setMethodclazz(jobVo.getMethodclazz());
            mJob.setGroupName(jobVo.getMethodclazz());
        }
        if(jobVo.getMethodname()!=null){
            mJob.setMethodname(jobVo.getMethodname());
            mJob.setTigger(jobVo.getMethodclazz()+"_"+jobVo.getMethodname());
        }
        if(jobVo.getNote()!=null){
            mJob.setNote(jobVo.getNote());
        }
        mJobService.updateById(mJob);
        quarztUtils.updataQuarzt(mJob);
        return Result.successInfo("更新成功");
    }

    @GetMapping("/stop")
    public JSONObject stopJob(@RequestParam("id")String id){
        MJob mJob=mJobService.getById(id);
        if(mJob == null){
            return Result.errorInfo("任务不存在");
        }
        if(QuartzStatusEnum.STOP.getStatus().equals(mJob.getStatus())){
            return Result.errorInfo("任务已暂停，无需暂停");
        }
        mJob.setStatus(QuartzStatusEnum.STOP.getStatus());
        quarztUtils.stopQuarzt(mJob);
        mJobService.updateById(mJob);
        return Result.successInfo("任务暂停成功");
    }

    @PostMapping("/execute")
    public JSONObject execute(@RequestBody JSONObject obj){
        if(!obj.containsKey("id")){
            return Result.errorInfo("id不存在");
        }
        String id=obj.getString("id");
        MJob mJob=mJobService.getById(id);
        if(mJob == null){
            return Result.errorInfo("job任务不存在");
        }
        quarztUtils.execOne(mJob);
        return Result.successInfo("执行成功");
    }

    @GetMapping("/start")
    public JSONObject startJob(@RequestParam("id")String id){
        MJob mJob=mJobService.getById(id);
        if(mJob == null){
            return Result.errorInfo("任务不存在");
        }
        if(QuartzStatusEnum.RUN.getStatus().equals(mJob.getStatus())){
            return Result.errorInfo("任务正在运行中，无需启动");
        }
        quarztUtils.startQuarzt(mJob);
        mJob.setStatus(QuartzStatusEnum.RUN.getStatus());
        mJobService.updateById(mJob);
        return Result.successInfo("任务开启成功");
    }


    @PostMapping("/add")
    public JSONObject add(@RequestBody JobVo jobVo){
        MJob mJob=new MJob();
        mJob.setClazz(MethodJob.class.getName());
        mJob.setCreatetime(new Date());
        mJob.setUpdatetime(new Date());
        mJob.setDeleted(0);
        mJob.setStatus(QuartzStatusEnum.RUN.getStatus());
        mJob.setGroupName(jobVo.getMethodclazz());
        mJob.setTigger(jobVo.getMethodclazz()+"_"+jobVo.getMethodname());
        BeanUtils.copyProperties(jobVo, mJob);
        mJobService.save(mJob);
        quarztUtils.addQuartz(mJob);
        return Result.successInfo("新增成功");
    }

}
